<?php
/**
 * Entity classe
 * @package Core
 * @subpackage Entity
 * @author kovacsricsi
 */
class Entity extends AEntity
{
	/**
	 * Load entity from database.
	 * @access protected
	 * @param int $id
	 * @return void
	 */
	protected function _load($id)
	{
		$sql = "SELECT * FROM " . $this->_tableName . " WHERE id = :id";

		$params = array(
			"id" => $id
		);

	    $result = QueryHandler::getOne($sql, $params);

	    if ($result == true) {
			$this->_entity = $result;
	    } else {
			throw new EntityNotFoundException($this->_tableName . " : " . $id);
	    }
	}

	/**
	 * Delete entity from database.
	 * @access public
	 * @throws EntityNotFoundException
	 * @return void
	 */
	public function delete()
	{
		if ($this->_readOnly) {
			throw new EntityNotFoundException("Entity is read only!");
		}

		$query = "DELETE FROM " . $this->_tableName . " WHERE id = :id";

		$params = array(
			"id" => $this->_entity["id"]
		);

		QueryHandler::execute($query, $params);

		$this->_entity  = array();
		$this->_changed = false;
	}

	/**
	 * Store entity to database.
	 * @access public
	 * @throws EntityNotFoundException
	 * @return void
	 */
	public function commit()
	{
		if ($this->_readOnly) {
			throw new EntityNotFoundException("Entity is read only!");
		}

	    if ($this->_changed) {
			$this->validate();

			$data = array();

			foreach($this->_columns as $column) {
				if (isset($this->_entity[$column["Field"]])) {
					$data[$column["Field"]] = $this->_entity[$column["Field"]];
				}
			}

			if (isset($this->_entity["id"])) {
				$this->_update($data);
			} else {
				unset($data["id"]);
				$this->_entity["id"] = $this->_insert($data);
			}
	    }
	}

	/**
	 * Validate data to store entity.
	 * @access public
	 * @return void
	 */
	 public function validate()
	 {

	 }

	 /**
	  * Insert new Entity to database.
	  * @access protected
	  * @param array $data
	  * @return int
	  */
	protected function _insert(array $data)
	{
		$query = "INSERT INTO " . $this->_tableName . " SET ";

		$tmp = array();

		foreach($data as $k => $v) {
				if ($v === "") {
					$tmp[] = " `" . $k . "` = NULL";
				} else {
					$tmp[] = " `" . $k . "` =:" . $k;
				}
		}

		$query .= join(",", $tmp);

		QueryHandler::execute($query, $data);

		$id = QueryHandler::getOne("SELECT  LAST_INSERT_ID() as id");
		return $id["id"];
	}

	 /**
	  * Update Entity in database.
	  * @access protected
	  * @param array $data
	  * @return void
	  */
	protected function _update(array $data)
	{
		$query = "UPDATE " . $this->_tableName . " SET ";

		$tmp = array();

		foreach($data as $k => $v) {
				if ($v === "") {
					$tmp[] = " `" . $k . "` = NULL";
				} else {
					$tmp[] = " `" . $k . "` =:" . $k;
				}
		}

		$query .= join(",", $tmp);

		$query .= " WHERE id = :id";

		$data["id"] = $this->_entity["id"];

		QueryHandler::execute($query, $data);
	}
}

?>
